package com.bub.pay.api.controller;

import com.bub.pay.core.entity.domain.SysRole;
import com.bub.pay.core.entity.domain.SysUser;
import com.bub.pay.core.entity.domain.SysUserRole;
import com.bub.pay.core.entity.dto.role.SysRoleDTO;
import com.bub.pay.core.entity.dto.user.SysUserDTO;
import com.bub.pay.core.entity.vo.user.*;
import com.bub.pay.core.manager.role.RoleManager;
import com.bub.pay.core.manager.user.UserManager;
import com.bub.pay.core.manager.user.role.UserRoleManager;
import com.bub.pay.framework.common.base.Cause;
import com.bub.pay.framework.common.base.Module;
import com.bub.pay.framework.common.entity.model.SessionModel;
import com.bub.pay.framework.common.exception.GlobalException;
import com.bub.pay.framework.common.util.CollectionUtil;
import com.bub.pay.framework.common.util.ContextHolder;
import com.bub.pay.framework.common.util.StrUtil;
import com.bub.pay.framework.wrap.annotation.SysLog;
import com.bub.pay.framework.wrap.annotation.SysLogType;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 总后台员工管理
 * staff代替user避免冲突
 *
 * @author Administrator
 */
@SysLogType("总后台员工管理")
@RestController
@RequestMapping("/admin/")
public class StaffController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(StaffController.class);

    @Resource
    private UserManager userManager;

    @Resource
    private RoleManager roleManager;

    @Resource
    private UserRoleManager userRoleManager;

    /**
     * 创建新员工
     *
     * @return
     */
    @SysLog("创建新员工")
    @PostMapping("user/add")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("employeeManage:employeeAccount:add")
    public Object addUser(@RequestBody AddSysUserVo userVo) {

        if (!StrUtil.checkParamByPattern("[a-zA-Z][A-Za-z0-9_]{3,9}", userVo.getUserName())) {
            logger.error("总管理-添加员工|请求参数不正确|用户名必须以字母开头4-10位数字'_'|参数|{}", userVo);
            throw new GlobalException(Module.admin, Cause.admin_add_user_username_err);
        }
        if (!StrUtil.checkParamByPattern("[A-Za-z0-9_\\u4e00-\\u9fa5]{2,6}", userVo.getNickName())) {
            logger.error("总管理-添加员工|请求参数不正确|昵称应为2-6位字母数字中文'_'|参数|{}", userVo);
            throw new GlobalException(Module.admin, Cause.admin_add_user_nickname_err);
        }
        if (!StrUtil.checkParamByPattern("\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}", userVo.getEmail())) {
            logger.error("总管理-添加员工|请求参数错误|邮件信息不正确|请求参数|{}", userVo.toString());
            throw new GlobalException(Module.admin, Cause.agent_mer_email_params_fail);
        }
        if (Objects.isNull(userVo.getRoleList())) {
            logger.error("总管理-添加员工|请求参数不正确|角色ID不正确|参数|{}", userVo);
            throw new GlobalException(Module.admin, Cause.admin_add_user_roleid_err);
        }
        if (!Objects.isNull(userVo.getState())) {
            if (!Arrays.asList(new Integer[]{1, 2}).contains(userVo.getState())) {
                logger.error("总管理-添加员工状态|请求参数不正确|用户状态不正确!|参数|{}", userVo);
                throw new GlobalException(Module.admin, Cause.admin_update_user_state_error);
            }
        }
        Example roleExample = new Example(SysRole.class);
        roleExample.createCriteria().andIn("id", userVo.getRoleList()).andEqualTo("delFlag", false);
        List<SysRole> roleList = roleManager.getByExample(roleExample);
        if (CollectionUtil.isNullOrEmpty(roleList) || (userVo.getRoleList().size() != roleList.size())) {
            logger.error("总管理-添加员工|请求参数不正确|角色ID不正确|参数|{}", userVo);
            throw new GlobalException(Module.admin, Cause.admin_add_user_roleid_err);
        }
        Example userExample = new Example(SysUser.class);
        userExample.createCriteria().andEqualTo("userName", userVo.getUserName());
        List<SysUser> userList = userManager.getByExample(userExample);
        if (!CollectionUtil.isNullOrEmpty(userList)) {
            logger.error("总管理-添加员工|请求参数不正确|用户名已经存在|参数|{}", userVo);
            throw new GlobalException(Module.admin, Cause.admin_add_user_username_exsits);
        }
        SessionModel model = ContextHolder.currentUserInfo();
        userVo.setExtendId(model.getExtendId());
        userVo.setUserType(model.getUserType());
        userVo.setCreateId(model.getUserId());
        return userManager.addUser(userVo);
    }


    @PostMapping("user/test")
    public void test() {
        System.out.println("==============================================");
    }


    /**
     * 查询角色
     */
    @SysLog("查询角色")
    @PostMapping("role/queryRole")
    @Transactional(readOnly = true)
    public Object queryRole(@RequestBody SysRoleVo vo) {
        Map<String, String> mapRoleId = new HashMap<>();
        if (!Objects.isNull(vo.getUserId())) {
            Example userRoleExample = new Example(SysUserRole.class);
            userRoleExample.createCriteria().andEqualTo("userId", vo.getUserId()).andEqualTo("delFlag", false);
            List<SysUserRole> userRoleList = userRoleManager.getByExample(userRoleExample);
            if (!CollectionUtil.isNullOrEmpty(userRoleList)) {
                userRoleList.forEach(e -> {
                    mapRoleId.put(e.getRoleId().toString(), e.getRoleId().toString());
                });
            }
        }
        Example example = new Example(SysRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", 3).andEqualTo("delFlag", false);
        List<SysRole> listRole = roleManager.getByExample(example);
        List<SysRoleDTO> listDto = new ArrayList<>();
        if (!CollectionUtil.isNullOrEmpty(listRole)) {
            listDto = listRole.stream().map(e -> {
                SysRoleDTO dto = new SysRoleDTO();
                BeanUtils.copyProperties(e, dto);
                if (StringUtils.isNotEmpty(mapRoleId.get(e.getId().toString()))) {
                    dto.setSelected(1);
                }
                return dto;
            }).collect(Collectors.toList());
        }
        return listDto;
    }

    /**
     * 修改员工信息
     *
     * @return
     */
    @SysLog("修改员工信息")
    @PostMapping("user/update")
    @RequiresPermissions("employeeManage:employeeAccount:update")
    public Object updateStaff(@RequestBody UpdateSysUserVo upUserVo) {
        if (Objects.isNull(upUserVo.getUserId())) {
            throw new GlobalException(Module.admin, Cause.admin_update_user_id_err);
        }
        SysUser bnSysUser = userManager.getById(upUserVo.getUserId());
        if (bnSysUser == null) {
            throw new GlobalException(Module.admin, Cause.admin_update_user_id_not_presence_err);
        }
        if (StringUtils.isNotBlank(upUserVo.getNickName())) {
            if (!StrUtil.checkParamByPattern("[A-Za-z0-9\\u4e00-\\u9fa5]{2,10}", upUserVo.getNickName())) {
                logger.error("总管理-修改员工昵称|请求参数不正确|昵称应为2-6位字母数字中文|参数|{}", upUserVo);
                throw new GlobalException(Module.admin, Cause.admin_add_user_nickname_err);
            }
        }
        if (!Objects.isNull(upUserVo.getState())) {
            if (!Arrays.asList(new Integer[]{1, 2}).contains(upUserVo.getState())) {
                logger.error("总管理-修改员工状态|请求参数不正确|修改用户状态!|参数|{}", upUserVo);
                throw new GlobalException(Module.admin, Cause.admin_update_user_state_error);
            }
        }
       /* if(StringUtils.isNotBlank(upUserVo.getPhone())){
            if(!StrUtil.checkParamByPattern("[0-9]{10,11}",upUserVo.getPhone())){
                logger.error("总管理-修改员工手机号|请求参数不正确|手机格式不正确,应为10或11数字!|参数|{}", upUserVo);
                throw new GlobalException(Module.admin, Cause.add_agent_phone_incorrect);
            }
        }*/
        if (StringUtils.isNotBlank(upUserVo.getEmail())) {
            if (!StrUtil.checkParamByPattern("\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}", upUserVo.getEmail())) {
                logger.error("总管理-修改员工邮箱|请求参数错误|请求参数|{}", upUserVo.toString());
                throw new GlobalException(Module.admin, Cause.agent_mer_email_params_fail);
            }
        }
        if (StringUtils.isNotBlank(upUserVo.getUserBindIp())) {
            List<String> listIp = Arrays.asList(upUserVo.getUserBindIp().split(";"));
            listIp.forEach(ip -> {
                boolean state = StrUtil.checkParamByPattern("(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)", ip);
                if (!state) {
                    logger.error("总管理-修改员工绑定IP|请求参数错误|请求参数|{}", upUserVo.toString());
                    throw new GlobalException(Module.admin, Cause.admin_user_update_ip_param_error);
                }
            });
        }
        if (!Objects.isNull(upUserVo.getRoleList())) {
            Example roleExample = new Example(SysRole.class);
            roleExample.createCriteria().andIn("id", upUserVo.getRoleList()).andEqualTo("delFlag", false);
            List<SysRole> roleList = roleManager.getByExample(roleExample);
            if (CollectionUtil.isNullOrEmpty(roleList) || (upUserVo.getRoleList().size() != roleList.size())) {
                logger.error("总管理-添加员工|请求参数不正确|角色ID不正确|参数|{}", upUserVo);
                throw new GlobalException(Module.admin, Cause.admin_add_user_roleid_err);
            }
        }
        roleManager.deleteUserRoleCache(upUserVo.getUserId());
        return userManager.updateUser(upUserVo);
    }


    /**
     * 获取员工信息
     *
     * @param vo
     * @return
     */
    @SysLog("获取员工信息")
    @RequestMapping("user/listPage")
    @Transactional(readOnly = true)
    @RequiresPermissions("employeeManage:employeeAccount:view")
    public Object listStaff(@RequestBody SysUserVo vo) {
        logger.info("总管理|获取员工信息|请求参数|{}", vo);
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(vo.getUserName())) {
            if (!StrUtil.checkParamByPattern("[a-zA-Z][A-Za-z0-9_]{3,9}", vo.getUserName())) {
                logger.error("总管理-查询员工|请求参数不正确|用户名必须以字母开头4-10位数字'_'|参数|{}", vo);
                throw new GlobalException(Module.admin, Cause.admin_add_user_username_err);
            }
            criteria.andLike("userName", vo.getUserName());
        }
        if (StringUtils.isNotBlank(vo.getNickName())) {
            if (!StrUtil.checkParamByPattern("[A-Za-z0-9_\\u4e00-\\u9fa5]{2,6}", vo.getNickName())) {
                logger.error("总管理-查询员工|请求参数不正确|昵称应为2-6位字母数字中文'_'|参数|{}", vo);
                throw new GlobalException(Module.admin, Cause.admin_add_user_nickname_err);
            }
            criteria.andLike("nickName", vo.getNickName());
        }
        if (!Objects.isNull(vo.getState())) {
            //状态(1：启用 2：禁用 ）
            if (!Arrays.asList(new Integer[]{1, 2}).contains(vo.getState())) {
                logger.error("总管理|获取员工信息|请求参数错误|请求参数|{}", vo);
                throw new GlobalException(Module.admin, Cause.params_fail);
            }
            criteria.andEqualTo("state", vo.getState());
        }
        if (!Objects.isNull(vo.getResetFlag())) {
            //重置标记 1重置 2不重置
            if (!Arrays.asList(new Integer[]{1, 2}).contains(vo.getResetFlag())) {
                logger.error("总管理|获取员工信息|请求参数错误|请求参数|{}", vo);
                throw new GlobalException(Module.admin, Cause.params_fail);
            }
            criteria.andEqualTo("resetFlag", vo.getResetFlag());
        }
        if (!Objects.isNull(vo.getBindGoogle())) {
            //是否绑定谷歌验证器.0:未绑定，1：绑定
            if (!Arrays.asList(new Integer[]{0, 1}).contains(vo.getBindGoogle())) {
                logger.error("总管理|获取员工信息|请求参数错误|请求参数|{}", vo);
                throw new GlobalException(Module.admin, Cause.params_fail);
            }
            criteria.andEqualTo("bindGoogle", vo.getBindGoogle());
        }

        Example exampleSysUserRole = new Example(SysUserRole.class);
        Example.Criteria sysUserRole = exampleSysUserRole.createCriteria().andEqualTo("delFlag", false);
        if (StringUtils.isNotBlank(vo.getRoleId())) {
            try {
                // 把字符串强制转换为数字
                Integer.valueOf(vo.getRoleId());
            } catch (Exception e) {
                logger.error("总管理|获取员工信息|请求参数错误,用户角色ID错误|请求参数|{}", vo);
                throw new GlobalException(Module.admin, Cause.params_fail);
            }
            sysUserRole.andEqualTo("roleId", vo.getRoleId());
        }
        List<SysUserRole> sysUserRoleList = userRoleManager.getByExample(exampleSysUserRole);

        criteria.andEqualTo("userType", 3).andEqualTo("delFlag", false);
        PageHelper.startPage(vo.getPageNo(), vo.getPageSize());
        List<SysUser> listEntity = userManager.getByExample(example);
        List<SysUserDTO> listDto = new ArrayList<>();
        if (!CollectionUtil.isNullOrEmpty(listEntity)) {
            listDto = listEntity.stream().map(e -> {
                SysUserDTO dto = new SysUserDTO();
                BeanUtils.copyProperties(e, dto);
                if (!CollectionUtil.isNullOrEmpty(sysUserRoleList)) {
                    List<Long> roleIds = new ArrayList<>();
                    sysUserRoleList.forEach(roleUser -> {
                        if (e.getId().equals(roleUser.getUserId())) {
                            roleIds.add(roleUser.getRoleId());
                        }
                    });
                    dto.setRoleIds(roleIds);
                }
                List<String> roleNames = new ArrayList<>();
                if (!CollectionUtil.isNullOrEmpty(dto.getRoleIds())) {
                    Example exampleRole = new Example(SysRole.class);
                    exampleRole.createCriteria().andIn("id", dto.getRoleIds()).andEqualTo("delFlag", false);
                    List<SysRole> roleList = roleManager.getByExample(exampleRole);
                    if (!CollectionUtil.isNullOrEmpty(roleList)) {
                        roleList.forEach(role -> roleNames.add(role.getName()));
                    }
                }
                dto.setRoleNames(roleNames);
                return dto;
            }).collect(Collectors.toList());
        }
        long total = 0;
        if (listEntity instanceof Page) {
            total = ((Page) listEntity).getTotal();
        }
        PageInfo pageInFo = new PageInfo<>(listDto);
        pageInFo.setTotal(total);

        return pageInFo;
    }

    /*  *//**
     * 修改用户支付密码
     *
     * @param updateUserPayPasswordVo 参数
     *//*
    @SysLog("修改用户支付密码_$(#updateUserPayPasswordVo.userId)")
    @RequestMapping("user/updatePayPassword")
    @RequiresPermissions("employeeManage:employeeAccount:updatePayPassword")
    public Object updatePayPassword(@Valid @RequestBody UpdateUserPayPasswordVo updateUserPayPasswordVo) {
        userManager.updatePayPassword(updateUserPayPasswordVo);
        return null;
    }*/

    /**
     * 修改用户密码
     *
     * @param updateUserPasswordVo 参数
     */
    @SysLog("修改用户密码_$(#updateUserPasswordVo.userId)")
    @RequestMapping("user/updatePassword")
    @RequiresPermissions("employeeManage:employeeAccount:updatePassword")
    public Object updatePassword(@Valid @RequestBody UpdateUserPasswordVo updateUserPasswordVo) {
        userManager.updatePassword(updateUserPasswordVo);
        return null;
    }

    /*  *//**
     * 重置用户谷歌密钥
     *
     * @param resetUserGoogleSecretVo 参数
     *//*
    @SysLog("重置用户谷歌密钥_$(#resetUserGoogleSecretVo.userId)")
    @RequestMapping("user/resetGoogleSecret")
    @RequiresPermissions("employeeManage:employeeAccount:resetGoogleSecret")
    public Object resetGoogleSecret(@Valid @RequestBody ResetUserGoogleSecretVo resetUserGoogleSecretVo) {
        userManager.resetGoogleSecret(resetUserGoogleSecretVo);
        return null;
    }*/

    /**
     * 注销用户
     *
     * @param logoutUserVo 参数
     */
    @SysLog("注销用户_$(#logoutUserVo.userId)")
    @RequestMapping("user/logout")
    @RequiresPermissions("employeeManage:employeeAccount:logout")
    public Object logoutUser(@Valid @RequestBody LogoutUserVo logoutUserVo) {
        userManager.logoutUser(logoutUserVo);
        return null;
    }


    /**
     * 删除用户
     *
     * @param updateSysUserVo 参数
     */
    @SysLog("逻辑删除用户_$(#updateSysUserVo.userId)\")")
    @RequestMapping("user/delete")
    @RequiresPermissions("employeeManage:employeeAccount:delete")
    public Object delUser(@RequestBody UpdateSysUserVo updateSysUserVo) {

        return userManager.deleteUser(updateSysUserVo);
    }

    /**
     * 重置密码/谷歌验证码
     *
     * @param resetPwdOrCodeVo 参数
     */
    @SysLog("重置密码/谷歌验证码_$(#resetPwdOrCodeVo.userId)\")")
    @RequestMapping("user/reset")
    @RequiresPermissions("employeeManage:employeeAccount:resetGoogleSecret")
    public Object reset(@RequestBody ResetPwdOrCodeVo resetPwdOrCodeVo) {
        return userManager.resetPwdOrCode(resetPwdOrCodeVo);
    }


}
